from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.shortcuts import render, HttpResponse
import json
from cmdb.models import *
from controller.public.pagination import *
from django.db.models import Q


PAGE_SIZE = 10  # 每页显示条数
current_page_total = 10  # 分页下标

def base(request):
    context = {}
    context['hallo'] = 'ha ha ha'
    return render(request, 'base.html', context)
@login_required()
def index(request):
    #  服务器列表
    project_name = request.GET.get('project_name', '')
    in_ip = request.GET.get('in_ip', '')
    position = request.GET.get('position', '')
    service = request.GET.get('service', '')
    host_name = request.GET.get('host_name', '')
    status = request.GET.get('status', '')

    # 设置查询条件
    filters = {}
    if project_name:
        filters['project_name__icontains'] = project_name
    if in_ip:
        filters['in_ip__icontains'] = in_ip
    if position:
        filters['position__icontains'] = position
    if host_name:
        filters['host_name__icontains'] = host_name
    if status:
        filters['status'] = True if status == "UP" else False

    page_num = int(request.GET.get('p', 1))  # 页码
    servers = Server.objects.filter(**filters)

    if service:  # 服务名或端口查询
        Q_like = Q(service_name=service) | Q(port=service)
        services = Service.objects.filter(Q_like)
        svcs = [svc.server for svc in services]
        new_servers = []
        # 比较服务器列表里的服务器实例和服务表里服务器外键（也就是服务器实例）
        for svr in servers:
            if svr in svcs:
                new_servers.append(svr)
        servers = new_servers

    paginator = Paginator_help(page_num, servers, PAGE_SIZE, current_page_total, request)
    # 重置当前页面列表对象
    app = []
    for obj in paginator.current_page.object_list:
        services = Service.objects.filter(server=obj)
        setattr(obj, 'services', services)
        app.append(obj)

    paginator.current_page.object_list = app
    return render_to_response('cmdb/index.html', locals())


def server_add_page(request):
    # 新增机器页面
    return render_to_response('cmdb/server_add.html', locals())

def server_add(request):
    # 新增机器
    response = HttpResponse()
    data = json.loads(request.GET.get('data', ''))

    server = Server()
    server.project_name = data['project_name']
    server.in_ip = data['in_ip']
    server.ex_ip = data['ex_ip']
    server.position = data['position']
    server.save()

    response.write(json.dumps(u'成功'))
    return response

def server_edit_page(request, id):
    # 编辑机器页面
    server = Server.objects.get(pk=id)
    return render_to_response('cmdb/server_edit.html', locals())

def server_edit(request):
    # 编辑机器
    response = HttpResponse()
    data = json.loads(request.GET.get('data', ''))

    print(data)
    for i in data:
        print(i, data[i])
    id = data['id']
    project_name = data['project_name']
    position = data['position']
    in_ip = data['in_ip']
    ex_ip = data['ex_ip']

    server = Server.objects.get(pk=id)
    server.project_name = project_name
    server.position = position
    server.in_ip = in_ip
    server.ex_ip = ex_ip
    server.save()

    response.write(json.dumps(u'成功'))
    return response

def server_delete(request):
    # 删除机器信息
    response = HttpResponse()
    data = json.loads(request.POST.get('data', ''))
    id = int(data['id'])
    Server.objects.get(pk=id).delete()

    response.write(json.dumps(u'成功'))
    return response
@login_required
def postmachineinfo(request):
    # 提交服务器信息
    response = HttpResponse()
    data = json.loads(request.GET.get('data', ''))
    id = int(data['id'])
    print('update--->')
    server = Server.objects.get(pk=id)
    data = get_info(server.in_ip)
    server.os_version = data['sysinfo']
    server.host_name = data['host_name']
    server.os_kernel = data['os_kernel']
    server.cpu_model = data['cpu']
    server.cpu_count = data['cpu_count']
    server.cpu_cores = data['cpu_cores']
    server.mem = data['mem']
    server.disk = data['disk']
    server.status = True
    server.max_open_files = get_ulimit(server.in_ip)
    server.uptime = get_uptime(server.in_ip)
    server.save()

    # set_service_port(server)  # 设置服务端口信息
    response.write(json.dumps(u'成功'))
    return response

def set_service_port(server):
    # 设置服务端口信息
    services = Service.objects.filter(server=server)
    result = get_service_port(server.in_ip)
    new_srv_name = result.keys()  # 客户端抓取的数据
    old_srv_name = [obj.service_name for obj in services]  # 数据库查询的数据
    add_services = list(set(new_srv_name) - set(old_srv_name))  # 新增的服务
    delete_services = list(set(old_srv_name) - set(new_srv_name))  # 删除的服务
    update_services = list(set(new_srv_name) & set(old_srv_name))  # 更新的服务
    add_data = {}  # 新增服务和端口号
    update_data = {}  # 更新的服务和端口号
    for value in result:
        if value in add_services:
            add_data[value] = result[value]
        if value in update_services:
            update_data[value] = result[value]
    # 新增服务
    for ad in add_data:
        values = add_data[ad]
        for val in values:
            Service.objects.create(server=server, service_name=ad, port=val)

    # 删除服务
    for delt in delete_services:
        Service.objects.filter(server=server, service_name=delt).delete()

    # 更新服务
    for update in update_data:
        new = update_data[update]  # 需要更新的服务的端口
        services = Service.objects.filter(server=server, service_name=update)
        old = [srv.port for srv in services]  # 旧的服务的端口

        adds = list(set(new) - set(old))  # 增加的端口
        deletes = list(set(old) - set(new))  # 删除的端口

        for add in adds:
            Service.objects.create(server=server, service_name=update, port=add)
        for delete in deletes:
            Service.objects.filter(server=server, service_name=update, port=delete).delete()

def agent_api(request):
    response = HttpResponse()
    apidata = str(request.GET)
    with open('E:\pylearn\madman\json.txt', 'r+') as ff:
        ff.write(apidata)
    response.write(json.dumps(u'成功'))
    return response

def show_api(request):
    apidata
    return render(request, 'cmdb/api.html', apidata)